package com.yl.chainStore.services.impl

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.baomidou.mybatisplus.core.toolkit.Wrappers
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.yl.chainStore.common.Constants
import com.yl.chainStore.common.enums.Status
import com.yl.chainStore.common.enums.TypeEnum
import com.yl.chainStore.entity.customer.CustomerDeptConfig
import com.yl.chainStore.entity.customer.CustomerInfo
import com.yl.chainStore.entity.pay.*
import com.yl.chainStore.entity.sick.CustomerSubscribeItem
import com.yl.chainStore.entity.sick.CustomerSubscribeLog
import com.yl.chainStore.entity.sick.SickCustomerAccessLog
import com.yl.chainStore.entity.sick.SickMedicalRecordsDetail
import com.yl.chainStore.entity.system.CompanyDeptOtherConfig
import com.yl.chainStore.entity.company.CompanySmsModelType
import com.yl.chainStore.entity.company.SickCustomerAccessLogModel
import com.yl.chainStore.entity.user.CompanyUserMedicalHistoryModelType
import com.yl.chainStore.entity.warehouse.TechnologyProcessing
import com.yl.chainStore.entity.warehouse.TechnologyProcessingPlant
import com.yl.chainStore.mapper.customer.CustomerDeptConfigMapper
import com.yl.chainStore.mapper.customer.CustomerInfoMapper
import com.yl.chainStore.mapper.pay.*
import com.yl.chainStore.mapper.sick.*
import com.yl.chainStore.mapper.system.CompanyDeptOtherConfigMapper
import com.yl.chainStore.mapper.company.CompanySmsModelTypeMapper
import com.yl.chainStore.mapper.company.SickCustomerAccessLogModelDetailMapper
import com.yl.chainStore.mapper.company.SickCustomerAccessLogModelMapper
import com.yl.chainStore.mapper.user.CompanyUserMedicalHistoryModelTypeMapper
import com.yl.chainStore.mapper.warehouse.TechnologyProcessingDetailMapper
import com.yl.chainStore.mapper.warehouse.TechnologyProcessingMapper
import com.yl.chainStore.mapper.warehouse.TechnologyProcessingPlantMapper
import com.yl.chainStore.payrule.item.ItemRuleTypeEnum
import com.yl.chainStore.payrule.order.OrderRuleTypeEnum
import com.yl.chainStore.pojo.vo.company.SickCustomerAccessLogModelSelectVo
import com.yl.chainStore.pojo.vo.customer.CustomerSelectVo
import com.yl.chainStore.pojo.vo.pay.*
import com.yl.chainStore.pojo.vo.sick.CustomerSubscribeLogSelectVo
import com.yl.chainStore.pojo.vo.sick.SickCustomerAccessLogSelectVo
import com.yl.chainStore.pojo.vo.sick.SickMedicalRecordsDetailSelectVo
import com.yl.chainStore.pojo.vo.warehouse.TechnologyProcessingMapperVo
import com.yl.chainStore.pojo.vo.warehouse.UpdateItemConfigVo
import com.yl.chainStore.services.*
import com.yl.chainStore.services.pay.ISysCompanyPayItemService
import com.yl.chainStore.services.pay.ISysCompanyPayItemTypeService
import com.yl.chainStore.services.sick.ICustomerSubscribeLogService
import com.yl.chainStore.util.getDays
import com.yl.chainStore.util.timeFormat
import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import com.yl.users.services.ICompanyDeptService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.math.BigDecimal
import java.math.RoundingMode
import java.util.*

/**
 * @description :公司部门业务处理实现
 */
@Service
class WebCompanyDeptServiceImpl(
	private val technologyProcessingDetailMapper: TechnologyProcessingDetailMapper,
	private val technologyProcessingMapper: TechnologyProcessingMapper,
	private val customerDeptConfigMapper: CustomerDeptConfigMapper,
	private val sysCompanyPayItemMapper: SysCompanyPayItemMapper,
	private val sysCompanyPayItemTypeMapper: SysCompanyPayItemTypeMapper,

	private val sickMedicalRecordsDetailMapper: SickMedicalRecordsDetailMapper,
	private val sickCustomerAccessLogMapper: SickCustomerAccessLogMapper,

	private val customerSubscribeItemMapper: CustomerSubscribeItemMapper,
	private val payCompanyCouponsModelMapper: PayCompanyCouponsModelMapper,
	private val payCustomerOrderMapper: PayCustomerOrderMapper,
	private val customerInfoMapper: CustomerInfoMapper,
	private val customerSubscribeLogMapper: CustomerSubscribeLogMapper,
	private val payCompanyCollectionLogMapper: PayCompanyCollectionLogMapper,
	private val sickMedicalRecordsMapper: SickMedicalRecordsMapper,

	private val payCustomerOrderItemDiscountRuleMapper: PayCustomerOrderItemDiscountRuleMapper,
	private val payOrderDiscountRuleMapper: PayOrderDiscountRuleMapper,

	private val companyDeptOtherConfigMapper: CompanyDeptOtherConfigMapper,

	private val companySmsModelTypeMapper: CompanySmsModelTypeMapper,

	private val sickCustomerAccessLogModelMapper : SickCustomerAccessLogModelMapper,
	private val sickCustomerAccessLogModelDetailMapper: SickCustomerAccessLogModelDetailMapper,


	private val companyUserMedicalHistoryModelTypeMapper: CompanyUserMedicalHistoryModelTypeMapper,
	private val technologyProcessingPlantMapper: TechnologyProcessingPlantMapper,

	) : IWebCompanyDeptService {

	@Autowired
	lateinit var iSysCompanyPayItemService: ISysCompanyPayItemService

	@Autowired
	lateinit var iSysCompanyPayItemTypeService: ISysCompanyPayItemTypeService

	@Autowired
	lateinit var iWebCompanyService: IWebCompanyService

	@Autowired
	lateinit var iWebSystemService: IWebSystemService

	@Autowired
	lateinit var iCustomerSubscribeLogService: ICustomerSubscribeLogService

	@Autowired
	lateinit var iCustomerInfoService: ICustomerInfoService

	@Autowired
	lateinit var iTechnologyProcessingService: ITechnologyProcessingService

	@Autowired
	lateinit var iCompanyDeptService: ICompanyDeptService

	companion object {
		private val log = LoggerFactory.getLogger(IWebCompanyDeptService::class.java)
	}

	override fun processAdd(en: TechnologyProcessing): ResponseBody {

		log.info("技加工记录对象en{}", en)
		technologyProcessingMapper.insert(en)

		//插入技加工详情
		for (i in en.details!!) {
			i.processLogId = en.id
			log.info("技加工详情订单details{}", i)

			technologyProcessingDetailMapper.insert(i)
		}

		return returnSuccess()
	}



	override fun processListByPage(
		vo: TechnologyProcessingMapperVo
	): Page<TechnologyProcessing> {
		log.info("技加工记录对象：，vo：{}", vo)
		val page = Page<TechnologyProcessing>(vo.current, vo.size)
		val processListByPage = technologyProcessingMapper.getProcessListByPage(page, vo)
		val record = processListByPage.records
		for (i in record) {
			i.details = iTechnologyProcessingService.processDetail(i.id)
		}
		return processListByPage
	}


	override fun addPayItem(item: SysCompanyPayItem, vo: UpdateItemConfigVo): ResponseBody {
		log.info("部门管理 ==> 添加私有服务项目item:{} vo:{}", item, vo)
		if (item.deptId == null) {
			item.deptId = getContext().subCompanyId
		}
		val result = iWebSystemService.addPayItem(item)
		if (result.code != ErrorCode.SUCCESS.code) {
			return result
		}
		vo.deptId = item.deptId!!
		vo.itemId = item.id

		return iSysCompanyPayItemService.setPayItemDeptConfig(vo)
	}

	override fun updatePayItem(item: SysCompanyPayItem, vo: UpdateItemConfigVo): ResponseBody {
		log.info("部门管理 ==> 修改私有服务项目item:{} vo:{}", item, vo)
		val oldItem = sysCompanyPayItemMapper.selectById(item.id) ?: return returnError(
			ErrorCode.DATA_IS_NOT_FIND,
			"未找到该收费项目，请刷新重试"
		)
		if (oldItem.deptId != null) {
			val updateItem = iSysCompanyPayItemService.updateItem(item)
			if (updateItem.bodyIsError()) {
				return updateItem
			}
		}
		return iSysCompanyPayItemService.setPayItemDeptConfig(vo)
	}

	override fun getCustomerPage(vo: CustomerSelectVo): Page<CustomerInfo> {
		log.info("部门管理 ==> 获取患者信息 ：vo：{}", vo)
		if(vo.companyId == null){
			vo.companyId = getContext().companyId
		}
		if(vo.deptId == null){
			vo.deptId = getContext().subCompanyId
		}
		val page = customerDeptConfigMapper.selectDeptCustomerPage(Page(vo.current,vo.size), vo, vo.deptId!!)
		for(info in page.records){
			info.showRules = iCustomerInfoService.getShowRuleByOrderDetail(info.id,vo.deptId!!)
		}

		return page
	}

	override fun setDeptConfig(config: CustomerDeptConfig): ResponseBody {
		log.info("部门管理 ==> 部门添加患者 ：config{}", config)
		val list = customerDeptConfigMapper.selectList(
			Wrappers.query<CustomerDeptConfig?>().eq("customer_id", config.customerId)
				.eq("dept_id", config.deptId)
		)
		if (list.isNullOrEmpty()) {
			customerDeptConfigMapper.insert(config)
		} else {
			config.id = list[0].id
			customerDeptConfigMapper.updateById(config)
		}
		return returnSuccess()
	}

	override fun getCustomerDeptConfig(customerId: Long, subCompanyId: Long): CustomerDeptConfig? {
		val list = customerDeptConfigMapper.selectList(
			Wrappers.query<CustomerDeptConfig?>().eq("customer_id", customerId)
				.eq("dept_id", subCompanyId)
		)
		return if (list.isEmpty()) {
			null
		} else {
			list[0]
		}
	}

	override fun setUserToCustomer(config: CustomerDeptConfig): ResponseBody {
		log.info("部门管理 ==> 设置患者部门配置 ：config{}", config)
		val selectList = customerDeptConfigMapper.selectList(
			Wrappers.query<CustomerDeptConfig?>()
				.eq("dept_id", config.deptId).eq("customer_id", config.deptId)
		)
		if (selectList.isEmpty()) {
			customerDeptConfigMapper.insert(config)
			return returnSuccess()
		}
		val dbConfig = selectList[0]
		dbConfig.firstChargeUserId = config.firstChargeUserId
		dbConfig.secondChargeUserId = config.secondChargeUserId
		dbConfig.thirdChargeUserId = config.thirdChargeUserId
		customerDeptConfigMapper.updateById(dbConfig)
		return returnSuccess()

	}




	override fun getPayItemPage(
		page: Page<SysCompanyPayItem>,
		vo: SystemCompanyPayItemSelectVo,
		deptId: Long
	): Page<SysCompanyPayItem> {
		log.info("部门管理 ==> 物品分页 vo:{}", vo)
		vo.types = listOf(TypeEnum.PAY_ITEM_GOODS, TypeEnum.PAY_ITEM_SERVICE)
		return sysCompanyPayItemMapper.deptSelectItemPage(page, vo, vo.typeId, deptId)
	}

	override fun getPayItemList(vo: SystemCompanyPayItemSelectVo, deptId: Long): List<SysCompanyPayItem> {
		log.info("部门管理 ==> 物品列表 vo:{}", vo)
		vo.types = listOf(TypeEnum.PAY_ITEM_GOODS, TypeEnum.PAY_ITEM_SERVICE)
		return sysCompanyPayItemMapper.deptSelectItemList(vo, vo.typeId, deptId)
	}


	override fun getItemTypeList(vo: SysCompanyPayItemTypeSelectVo): MutableList<SysCompanyPayItemType> {
		log.info("部门操作 ===> 获取部门收费项目类型 vo：{}", vo)
		vo.itemTypes = listOf(TypeEnum.PAY_ITEM_GOODS, TypeEnum.PAY_ITEM_SERVICE)
		return sysCompanyPayItemTypeMapper.getList(vo)
	}

	override fun getMedicalRecordsPage(
		deptId: Long,
		page: Page<SickMedicalRecordsDetail>,
		vo: SickMedicalRecordsDetailSelectVo
	): Page<SickMedicalRecordsDetail> {
		log.info("部门操作 ===> 分院来访记录 deptId：{}，page：{}，vo:{}", deptId, page, vo)
		vo.deptId = deptId
		return sickMedicalRecordsDetailMapper.getPage(page, vo)
	}

	override fun getMedicalRecordsCount(deptId: Long, vo: SickMedicalRecordsDetailSelectVo): Int {
		log.info("部门操作 ===> 分院来访记录 deptId：{}，vo:{}", deptId, vo)
		vo.deptId = deptId
		return sickMedicalRecordsDetailMapper.selectUserRecordsDetailCount(vo)
	}

	override fun getCustomerSubscribeItemList(): MutableList<CustomerSubscribeItem> {
		log.info("部门操作 ===> 客户预约项目")
		return customerSubscribeItemMapper.getDeptItemList(getContext().companyId, getContext().subCompanyId)
	}

	override fun createCustomerCouponsModel(model: PayCompanyCouponsModel): ResponseBody {
		log.info("部门操作 ===> 添加一个优惠卷模板 model:{}", model)
		try {
			val validationSelf = model.getOtherContentObj().validationSelf()
			if (validationSelf.bodyIsError()) {
				return validationSelf
			}
		} catch (e: Exception) {
			e.printStackTrace()
			return returnError(ErrorCode.DATA_SAVE_FAILED, "优惠规则格式错误")
		}

		payCompanyCouponsModelMapper.insert(model)
		return returnSuccess()
	}

	override fun getCustomerCouponsModelList(vo: PayCompanyCouponsModelSelectVo): List<PayCompanyCouponsModel> {
		return payCompanyCouponsModelMapper.getModelList(vo)
	}

	override fun collection(
		payCompanyCollectionLog: PayCompanyCollectionLog
	): ResponseBody {
		log.info("部门操作 ===> 分院收款 payCompanyCollectionLog:{}", payCompanyCollectionLog)
		if (payCompanyCollectionLog.deptId == null) {
			payCompanyCollectionLog.deptId = getContext().subCompanyId
		}
		iWebCompanyService.collection(payCompanyCollectionLog)
		return returnSuccess()
	}

	override fun getSubScribeListByDate(vo: CustomerSubscribeLogSelectVo): List<List<CustomerSubscribeLog>> {
		log.info("订单管理 ==> 按日期查询预约：vo：{}", vo)
		if(vo.subCompanyId == null){
			vo.subCompanyId = getContext().subCompanyId
		}
		if(vo.subLogType == null){
			vo.subLogType = TypeEnum.CUSTOMER_SUBSCRIBE_TYPE_NORMAL
		}
		val resList = mutableListOf<List<CustomerSubscribeLog>>()
		if (vo.type.equals("day")) {
			//查询单个开始日期,直接返回
			resList.add(customerSubscribeLogMapper.getSubscribeLogList(vo))
		} else {
			if (vo.beginTime != null && vo.endTime != null) {
				//对查询到得数组进行处理
				val daysList = getDays(vo.beginTime!!, vo.endTime!!)
				for (i in daysList) {
					vo.beginTime = i
					vo.type = "day"
					resList.add(customerSubscribeLogMapper.getSubscribeLogList(vo))
				}
			}

		}
		return resList
	}


	override fun getSubscribeLogList(vo: CustomerSubscribeLogSelectVo): List<CustomerSubscribeLog> {
		log.info("订单管理 ==> 查询预约列表：vo：{}", vo)
		if(vo.subCompanyId == null){
			vo.subCompanyId = getContext().subCompanyId
		}
		if(vo.subLogType == null){
			vo.subLogType = TypeEnum.CUSTOMER_SUBSCRIBE_TYPE_NORMAL
		}
		val subscribeLogList = customerSubscribeLogMapper.getSubscribeLogList(vo)
		for (subLog in subscribeLogList) {
			if (subLog.itemIdsShow != null) {
				subLog.itemNames = iCustomerSubscribeLogService.getSubscribeItemsByIdsStr(subLog.itemIdsShow!!)
			}
		}
		return subscribeLogList
	}

	override fun getSubscribeLogPage(vo: CustomerSubscribeLogSelectVo): Page<CustomerSubscribeLog> {
		log.info("订单管理 ==> 查询预约分页：vo：{}", vo)
		if(vo.subCompanyId == null){
			vo.subCompanyId = getContext().subCompanyId
		}
		if(vo.subLogType == null){
			vo.subLogType = TypeEnum.CUSTOMER_SUBSCRIBE_TYPE_NORMAL
		}
		val subscribeLogPage = customerSubscribeLogMapper.getSubscribeLogCancelPage(
			Page(vo.current,vo.size),vo)
		for (subLog in subscribeLogPage.records) {
			if (subLog.itemIdsShow != null) {
				subLog.itemNames = iCustomerSubscribeLogService.getSubscribeItemsByIdsStr(subLog.itemIdsShow!!)
			}
		}
		return subscribeLogPage
	}

	override fun getSubscribeLogCount(vo: CustomerSubscribeLogSelectVo): Int {
		log.info("订单管理 ==> 查询预约分页：vo：{}", vo)
		if(vo.subCompanyId == null){
			vo.subCompanyId = getContext().subCompanyId
		}
		if(vo.subLogType == null){
			vo.subLogType = TypeEnum.CUSTOMER_SUBSCRIBE_TYPE_NORMAL
		}
		return customerSubscribeLogMapper.getSubscribeLogCount(vo)
	}

	override fun toChargeList(vo: PayCustomOrderToChargeVo): Page<PayCustomerOrder> {
		log.info("订单管理 ==> 查询待付款列表：vo：{}", vo)
		if(vo.subCompanyId != null){
			vo.subCompanyId = getContext().subCompanyId
		}
		vo.isPay = false
		val page = Page<PayCustomerOrder>(vo.current, vo.size)
		return payCustomerOrderMapper.getOrderPageByCharge(page, vo)
	}

	override fun toChargeCount(vo: PayCustomOrderToChargeVo): Int {
		vo.isPay = false
		if(vo.subCompanyId != null){
			vo.subCompanyId = getContext().subCompanyId
		}
		return payCustomerOrderMapper.getCountByCharge(vo)
	}

	override fun hasChargeList(vo: PayCustomOrderToChargeVo): Page<PayCustomerOrder> {
		log.info("订单管理 ==> 查询已付款列表：vo：{}", vo)
		if(vo.subCompanyId == null){
			vo.subCompanyId = getContext().subCompanyId
		}
		if(vo.companyId == null){
			vo.companyId = getContext().companyId
		}
		vo.isPay = true
		val page = Page<PayCustomerOrder>(vo.current, vo.size)
		return payCustomerOrderMapper.getOrderPageByCharge(page, vo)
	}

	override fun hasChargeCount(vo: PayCustomOrderToChargeVo):Int {
		vo.isPay = true
		if(vo.subCompanyId == null){
			vo.subCompanyId = getContext().subCompanyId
		}
		if(vo.companyId == null){
			vo.companyId = getContext().companyId
		}
		return payCustomerOrderMapper.getCountByCharge(vo)
	}

	override fun getOrderPage(vo: PayCustomerOrderSelectVo): Page<PayCustomerOrder>  {
		log.info("订单管理 ==> 查询待付款列表：vo：{}", vo)
		val page = Page<PayCustomerOrder>(vo.current, vo.size)
		return  payCustomerOrderMapper.getOrderPage(page, vo)
	}

	override fun getOrderList(vo: PayCustomerOrderSelectVo): List<PayCustomerOrder> {
		log.info("订单管理 ==> 查询待付款列表：vo：{}", vo)
		return  payCustomerOrderMapper.getOrderList( vo)
	}

	override fun cancelSubscribePage(vo: CustomerSubscribeLogSelectVo): Page<CustomerSubscribeLog> {
		//查出所有预约项目
		vo.status = Status.CANCEL
		vo.subLogType = TypeEnum.CUSTOMER_SUBSCRIBE_TYPE_NORMAL
		val page = Page<CustomerSubscribeLog>(vo.current, vo.size)

		val cancelSubscribeList = customerSubscribeLogMapper.getSubscribeLogPage(page, vo)
		for (i in cancelSubscribeList.records) {
			if (!i.itemIdsShow.isNullOrEmpty()) {
				i.itemNames = iCustomerSubscribeLogService.getSubscribeItemsByIdsStr(i.itemIdsShow!!)
			}
		}

		return cancelSubscribeList
	}

	override fun getAccessLogPage(
		page: Page<SickCustomerAccessLog>,
		vo: SickCustomerAccessLogSelectVo
	): Page<SickCustomerAccessLog> {
		if (vo.subCompanyId == null) {
			vo.subCompanyId = getContext().subCompanyId
		}
		return sickCustomerAccessLogMapper.getLogPage(page, vo)
	}

	override fun getAccessLogCount(vo: SickCustomerAccessLogSelectVo): Int {
		if(vo.subCompanyId == null){
			vo.subCompanyId = getContext().subCompanyId
		}
		return sickCustomerAccessLogMapper.getLogCount(vo)
	}

	override fun getAccessLogList(vo: SickCustomerAccessLogSelectVo): List<SickCustomerAccessLog> {
		if (vo.subCompanyId == null) {
			vo.subCompanyId = getContext().subCompanyId
		}
		return sickCustomerAccessLogMapper.getLogList(vo)
	}

	override fun getTodayNewCustomer(deptId: Long): Int {
		return customerInfoMapper.getTodayNewCustomer(deptId)
	}

	override fun getTodayNewSub(deptId: Long): Int {
		return customerSubscribeLogMapper.getTodayNewSub(deptId)
	}


	override fun todayStatistics(deptId: Long): Map<String, Any> {
		//新增患者
		val todayNewCustomer = getTodayNewCustomer(deptId)
		//新增预约
		val todayNewSub = getTodayNewSub(deptId)
		//实收金额
		val todayNewCollection = getTodayNewCollection(deptId)
		//随访人员
		val todayNewAccessLog = getTodayNewAccessLog(deptId)
		//今日就诊
		val todayNewSickMedicalRecords = getTodayNewSickMedicalRecords(deptId)
		val map = mutableMapOf<String, Any>()
		map["todayNewCustomer"] = todayNewCustomer
		map["todayNewSub"] = todayNewSub
		map["todayNewCollection"] =
			BigDecimal(todayNewCollection.div(Constants.OtherConfig.MONEY_TO_DB_DOUBLE)).setScale(
				2,
				RoundingMode.HALF_UP
			)
		map["todayNewAccessLog"] = todayNewAccessLog
		map["todayNewSickMedicalRecords"] = todayNewSickMedicalRecords
		return map

	}

	override fun getTodayNewSickMedicalRecords(deptId: Long): Int {
		return sickMedicalRecordsMapper.getTodayNewSickMedicalRecords(deptId)
	}

	override fun getTodayNewAccessLog(deptId: Long): Int {
		return sickCustomerAccessLogMapper.getTodayNewAccessLog(deptId)
	}

	override fun getTodayNewCollection(deptId: Long): Long {
		return payCompanyCollectionLogMapper.getTodayNewCollection(deptId)
	}

	override fun addItemPayDiscountRule(rule: PayCustomerOrderItemDiscountRule): ResponseBody {
		val validationSelf = rule.getOtherContentObj().validationSelf()
		rule.subCompanyId = getContext().subCompanyId
		if (validationSelf.bodyIsError()) {
			return validationSelf
		}
		payCustomerOrderItemDiscountRuleMapper.insert(rule)
		return returnSuccess()
	}

	override fun getItemPayDiscountRulePage(
		page: Page<PayCustomerOrderItemDiscountRule>,
		vo: PayCustomerOrderItemDiscountRuleSelectVo
	): Page<PayCustomerOrderItemDiscountRule> {
		return payCustomerOrderItemDiscountRuleMapper.getRulePage(page, vo)
	}

	override fun getItemPayDiscountRuleList(vo: PayCustomerOrderItemDiscountRuleSelectVo): List<PayCustomerOrderItemDiscountRule> {
		return payCustomerOrderItemDiscountRuleMapper.getRuleList(vo)
	}

	override fun getNowOpenItemDiscountRuleList(
		subCompanyId: Long,
		type: ItemRuleTypeEnum?
	): List<PayCustomerOrderItemDiscountRule> {
		val vo = PayCustomerOrderItemDiscountRuleSelectVo(
			companyId = getContext().companyId,
			subCompanyId = subCompanyId,
			status = Status.OPEN,
			nowTime = Date()
		)
		if (type != null) {
			vo.ruleType = type
		}
		return getItemPayDiscountRuleList(
			vo
		)
	}

	override fun addOrderPayDiscountRule(rule: PayOrderDiscountRule): ResponseBody {
		val validationSelf = rule.getOtherContentObj().validationSelf()
		rule.subCompanyId = getContext().subCompanyId
		if (validationSelf.bodyIsError()) {
			return validationSelf
		}
		payOrderDiscountRuleMapper.insert(rule)
		return returnSuccess()
	}

	override fun getOrderPayDiscountRulePage(
		page: Page<PayOrderDiscountRule>,
		vo: PayOrderDiscountRuleSelectVo
	): Page<PayOrderDiscountRule> {
		return payOrderDiscountRuleMapper.selectOrderRulePage(page, vo)
	}

	override fun getOrderPayDiscountRuleList(vo: PayOrderDiscountRuleSelectVo): List<PayOrderDiscountRule> {
		return payOrderDiscountRuleMapper.selectOrderRuleList(vo)
	}

	override fun getNowOpenOrderDiscountRuleList(
		subCompanyId: Long,
		type: OrderRuleTypeEnum?
	): List<PayOrderDiscountRule> {
		val vo = PayOrderDiscountRuleSelectVo(
			companyId = getContext().companyId,
			subCompanyId = subCompanyId,
			status = Status.OPEN,
			nowTime = Date()
		)
		if (type != null) {
			vo.ruleType = type
		}
		return getOrderPayDiscountRuleList(
			vo
		)
	}

	override fun addPayItemType(type: SysCompanyPayItemType): ResponseBody {
		if(type.superId != 0L){
			val selectById = sysCompanyPayItemTypeMapper.selectById(type.superId)
			type.itemType = selectById.itemType
		}else{
			if(type.itemType != TypeEnum.PAY_ITEM_SERVICE &&
					type.itemType != TypeEnum.PAY_ITEM_GOODS){
				returnError(ErrorCode.DATA_SAVE_FAILED,
				"类型选择错误")
			}
		}

		sysCompanyPayItemTypeMapper.insert(type)
		return returnSuccess()
	}

	override fun delPayItemType(typeId: Long): ResponseBody {
		val sysCompanyPayItemType = sysCompanyPayItemTypeMapper.selectById(typeId) ?: return returnError(
			ErrorCode.DATA_IS_NOT_FIND,
			"未找到分类，请刷新重试"
		)
		if (sysCompanyPayItemType.deptId == null) {
			return returnError(ErrorCode.OPERATION_DATA_ERROR, "该类型不能删除，请联系管理员")
		}
		return iSysCompanyPayItemTypeService.delType(sysCompanyPayItemType.id)
	}

	override fun delPayItem(id: Long): ResponseBody {
		return iSysCompanyPayItemService.deptDelPayItem(id, getContext().subCompanyId)
	}

	override fun getOtherConfig(subCompanyId: Long): CompanyDeptOtherConfig? {
		val list = companyDeptOtherConfigMapper.selectList(
			Wrappers.query<CompanyDeptOtherConfig?>()
				.eq("sub_company_id", subCompanyId)
		)
		if(list.isEmpty()){
			return null
		}
		return list[0]
	}

	override fun getOrderPrintTitle(subCompanyId: Long): String {
		val otherConfig = getOtherConfig(subCompanyId)
		if(otherConfig?.orderPrintTitle != null && otherConfig.orderPrintTitle!!.isNotEmpty()){
			return otherConfig.orderPrintTitle!!
		}
		val dept = iCompanyDeptService.getDept(subCompanyId)
		if(dept != null){
			return dept.name
		}
		return ""

	}

	override fun getOweOrderPrintTitle(subCompanyId: Long): String {
		val otherConfig = getOtherConfig(subCompanyId)
		if(otherConfig?.oweOrderPrintTitle != null && otherConfig.oweOrderPrintTitle!!.isNotEmpty()){
			return otherConfig.oweOrderPrintTitle!!
		}
		val dept = iCompanyDeptService.getDept(subCompanyId)
		if(dept != null){
			return dept.name
		}
		return ""
	}

	override fun getOtherConfigWorkTimeStr(subCompanyId: Long): String {
		val otherConfig = getOtherConfig(subCompanyId)
		var show = ""
		if(otherConfig != null){
			show = if(otherConfig.workStartTime != null){
				timeFormat(otherConfig.workStartTime!!)
			}else{
				"08:00:00"
			}
			show += " - "
			show += if(otherConfig.workEndTime != null){
				timeFormat(otherConfig.workEndTime!!)
			}else{
				"18:00:00"
			}
		}
		return show
	}

	override fun addSmsModelType(type: CompanySmsModelType): ResponseBody {
		if(type.typeName.isEmpty()){
			return returnError(ErrorCode.PARAM_EMPTY,"请输入类型名称")
		}
		companySmsModelTypeMapper.insert(type)
		return returnSuccess()
	}

	override fun getSmsModelTypeList(subCompanyId: Long): List<CompanySmsModelType> {
		return companySmsModelTypeMapper.selectList(
			Wrappers.query<CompanySmsModelType?>()
				.eq("sub_company_id",subCompanyId)
				.eq("enabled",1)
				.orderByAsc("order_num")
		)
	}

	override fun createAccessLogModel(model: SickCustomerAccessLogModel): ResponseBody {
		if(model.details == null || model.details!!.size == 0){
			return returnError(ErrorCode.DATA_SAVE_FAILED,"请添加随访模版内容")
		}
		val maxOrderNum = sickCustomerAccessLogModelMapper.getLastOrderNum(model.subCompanyId)?:0
		model.orderNum = maxOrderNum+1
		sickCustomerAccessLogModelMapper.insert(model)
		var orderNum = 1
		for(detail in model.details!!){
			if(detail.timeNumber < 0){
				return returnError(ErrorCode.DATA_SAVE_FAILED,"间隔时间不能小于0")
			}
			detail.orderNum = orderNum
			detail.modelId = model.id
			sickCustomerAccessLogModelDetailMapper.insert(detail)
			orderNum++
		}
		return returnSuccess()
	}

	override fun getAccessLogModelPage(vo: SickCustomerAccessLogModelSelectVo): Page<SickCustomerAccessLogModel> {
		if(vo.subCompanyId == null){
			vo.subCompanyId = getContext().subCompanyId
		}
		return sickCustomerAccessLogModelMapper.selectPageByVo(Page(vo.current,vo.size),vo)
	}

	override fun getAccessLogModelList(vo: SickCustomerAccessLogModelSelectVo): List<SickCustomerAccessLogModel> {
		if(vo.subCompanyId == null){
			vo.subCompanyId = getContext().subCompanyId
		}
		return sickCustomerAccessLogModelMapper.selectListByVo(vo)
	}

	override fun delAccessLogModel(id: Long): ResponseBody {
		val model = sickCustomerAccessLogModelMapper.selectById(id)?:return returnError(ErrorCode.DATA_IS_NOT_FIND,"未找到模版，请刷新重试")
		model.updateUserId = getContext().userId
		model.updateTime = Date()
		model.enabled = 0
		sickCustomerAccessLogModelMapper.updateById(model)
		return returnSuccess()
	}

	override fun addMedicalHistoryModelType(modelType: CompanyUserMedicalHistoryModelType): ResponseBody {
		log.info("公司 ==> 添加病历模板类型:modelType:{}", modelType)
		companyUserMedicalHistoryModelTypeMapper.insert(modelType)
		return returnSuccess()
	}

	override fun getMedicalHistoryTypeModelList(): MutableList<CompanyUserMedicalHistoryModelType> {
		return companyUserMedicalHistoryModelTypeMapper.selectTypeModelByCompanyId(getContext().companyId, getContext().subCompanyId)
	}


	override fun getMedicalHistoryTypeList(): MutableList<CompanyUserMedicalHistoryModelType> {
		return companyUserMedicalHistoryModelTypeMapper.selectList(Wrappers.query<CompanyUserMedicalHistoryModelType?>()
			.eq("company_id", getContext().companyId)
			.eq("sub_company_id", getContext().subCompanyId)
		)
	}

	override fun getTechnologyPlantList(companyId: Long): List<TechnologyProcessingPlant> {
		return technologyProcessingPlantMapper.selectList(QueryWrapper<TechnologyProcessingPlant?>().eq("company_id", companyId))

	}




}

